package pers.qianyu.month_202011.date_20201118;

import java.util.*;

/**
 * 15. 三数之和
 * https://leetcode-cn.com/problems/3sum/
 *
 * @author mizzle rain
 * @date 2020-11-18 15:39
 */
public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        ArrayList<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                break;
            }
            if (i != 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            List<List<Integer>> lists = twoSum(nums, i + 1, -nums[i]);
            res.addAll(lists);
        }
        return res;
    }

    private List<List<Integer>> twoSum(int[] nums, int left, int target) {
        ArrayList<List<Integer>> res = new ArrayList<>();
        int right = nums.length - 1;
        while (left < right) {
            int leftNum = nums[left];
            int rightNum = nums[right];
            int sum = leftNum + rightNum;

            if (sum > target) {
                while (left < right && rightNum == nums[right]) {
                    right--;
                }
            } else if (sum < target) {
                while (left < right && leftNum == nums[left]) {
                    left++;
                }
            } else {
                res.add(new ArrayList<>(Arrays.asList(leftNum, rightNum, -target)));
                while (left < right && leftNum == nums[left]) {
                    left++;
                }
                while (left < right && rightNum == nums[right]) {
                    right--;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        List<List<Integer>> result = new ThreeSum().threeSum(new int[]{-1, 0, 1, 2, -1, -4});
        System.out.println("result = " + result);
    }
}
